package com.example.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import java.util.Random;

@Aspect
public class OrderServiceAspect {

    // 1. 前置增强：使用完整包名com.example.service.OrderService
    @Before("execution(* com.example.service.OrderService.add(..)) || " +
            "execution(* com.example.service.OrderService.delete(..)) || " +
            "execution(* com.example.service.OrderService.find(..))")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

    // 2. 后置增强：使用完整包名
    @AfterReturning("execution(* com.example.service.OrderService.add(..)) || " +
            "execution(* com.example.service.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 3. 获取方法返回值并输出：使用完整包名
    @AfterReturning(pointcut = "execution(* com.example.service.OrderService.*(..))", returning = "result")
    public void afterReturningAdvice(Object result) {
        if (result != null) {
            System.out.println("方法返回值: " + result);
        }
    }

    // 4. 计算方法执行时间：使用完整包名
    @Around("execution(* com.example.service.OrderService.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed(); // 执行目标方法
        long endTime = System.currentTimeMillis();
        System.out.println("方法执行时间: " + (endTime - startTime) + "毫秒");
        return result;
    }

    // 5. 权限检查增强：使用完整包名
    @Before("execution(* com.example.service.OrderService.add(..)) || " +
            "execution(* com.example.service.OrderService.delete(..))")
    public void permissionCheck(JoinPoint joinPoint) throws Throwable {
        Random random = new Random();
        int permission = random.nextInt(2); // 生成0或1的随机数

        if (permission == 1) {
            System.out.println("权限检查: 没有权限执行此操作");
            // 抛出异常终止方法执行
            throw new RuntimeException("没有权限执行此操作");
        } else {
            System.out.println("权限检查: 有权限执行此操作");
        }
    }
}
